package cloud.hedou.abp.remote

import cloud.hedou.abp.starter.Server
import com.fasterxml.jackson.databind.ObjectMapper
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.slf4j.LoggerFactory
import retrofit2.Retrofit
import retrofit2.converter.jackson.JacksonConverterFactory
import java.util.concurrent.TimeUnit

internal class AbpHttpClient(
    private val server: Server,
    private val objectMapper: ObjectMapper
) : HttpClient {

    private val logger = LoggerFactory.getLogger(AbpHttpClient::class.java)

    val okHttpClient: OkHttpClient by lazy {
        OkHttpClient.Builder()
            .callTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)
            .addInterceptor(HeadersInterceptor())
            .addInterceptor(DynamicTimeoutInterceptor())
            .addInterceptor(DynamicUrlInterceptor(server.toMap()))
            .addInterceptor(HttpLoggingInterceptor(logger::info).setLevel(HttpLoggingInterceptor.Level.BODY))
            .build()
    }

    val retrofit: Retrofit by lazy {
        Retrofit.Builder()
            .baseUrl(server.url!!)
            .client(okHttpClient)
            .addConverterFactory(JacksonConverterFactory.create(objectMapper))
            .build()
    }

    override fun <T> create(klass: Class<T>): T {
        return retrofit.create(klass)
    }

}